package com.geek.jdbc.work2v2.dao;



import com.geek.jdbc.work2v2.entity.Customer;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 
 * @desc TODO
 * @data 2025/11/18
 */
public class BaseDao {

    //查询单个对象
    public Customer selectOne(Connection conn, String sql, Object... args) throws SQLException {
        Customer stu = null;

        //预编译SQL语句,获得语句对象
        PreparedStatement ppst = conn.prepareStatement(sql);
        for (int i = 0; i < args.length; i++) {
            //给?占位符传值
            ppst.setObject(i + 1, args[i]);
        }
        //执行查询
        ResultSet rs = ppst.executeQuery();
        while (rs.next()) {
            stu = new Customer(rs.getString(1), rs.getString(2),
                    rs.getString(3), rs.getDate(4));
        }
        return stu;
    }

    //查询多个个对象
    public List<Customer> selectAll(Connection conn, String sql, Object... args) throws SQLException {
        List<Customer> list = new ArrayList<>();

        //预编译SQL语句,获得语句对象
        PreparedStatement ppst = conn.prepareStatement(sql);
        try {
            for (int i = 0; i < args.length; i++) {
                //给?占位符传值
                ppst.setObject(i + 1, args[i]);
            }
        } catch (NullPointerException e) {
            System.out.println("开始查询所有信息...");
        }
        //执行查询
        ResultSet rs = ppst.executeQuery();
        while (rs.next()) {
            Customer stu = new Customer(rs.getString(1), rs.getString(2),
                    rs.getString(3), rs.getDate(4));

            list.add(stu);
        }
        return list;
    }

    //增删改
    public int update(Connection conn, String sql, Object... args) throws SQLException {
        PreparedStatement ppst = conn.prepareStatement(sql);
        for (int i = 0; i < args.length; i++) {
            //给?占位符传值
            ppst.setObject(i + 1, args[i]);
        }
        int i = ppst.executeUpdate();
        return i;
    }
}
